
from django.db import models

from app.models import BaseModel

# Create your models here.


class BookAuthor(BaseModel):
    name = models.CharField(
        max_length=100, verbose_name="作者名称", null=True, blank=True, db_comment='作者名称')
    introduction = models.TextField(
        verbose_name="人物简介", null=True, blank=True, db_comment='人物简介')
    cover_url = models.URLField(
        verbose_name="人物封面url", null=True, blank=True, db_comment='人物封面url')
    books = models.TextField(
        verbose_name="自写书", null=True, blank=True, db_comment='自写书')

    def __str__(self):
        return self.name or "未命名作者"

    class Meta:
        db_table = "dedao_book_author"
        verbose_name = "图书作者"
        verbose_name_plural = "03.图书作者"
        db_table_comment = '图书作者表'


class Book(BaseModel):
    name = models.CharField(
        max_length=100, verbose_name="书名", null=True, blank=True, db_comment='书名')
    author_ids = models.CharField(
        max_length=100, verbose_name="作者IDS", null=True, blank=True, db_comment='作者IDS')
    translation = models.CharField(
        max_length=100, verbose_name="翻译", null=True, blank=True, db_comment='翻译')
    price = models.DecimalField(
        max_digits=10, verbose_name="价格", decimal_places=2, null=True, blank=True, db_comment='价格')
    publish = models.CharField(
        max_length=100, verbose_name="出版社", null=True, blank=True, db_comment='出版社')
    publish_date = models.DateField(
        verbose_name="出版日期", null=True, blank=True, db_comment='出版日期')
    isbn = models.CharField(
        max_length=100, verbose_name="ISBN", null=True, blank=True, db_comment='ISBN')
    cover_url = models.URLField(
        verbose_name="封面url", null=True, blank=True, db_comment='封面url')
    tags = models.CharField(
        max_length=100, verbose_name="图书标签", null=True, blank=True, db_comment='图书标签')
    introduction = models.TextField(
        verbose_name="图书简介", null=True, blank=True, db_comment='图书简介')
    word_count = models.IntegerField(
        verbose_name="字数", null=True, blank=True, db_comment='字数')
    dedao_url = models.URLField(
        verbose_name="得到url", null=True, blank=True, db_comment='得到url')
    fanshu_url = models.URLField(
        verbose_name="帆书url", null=True, blank=True, db_comment='帆书url')
    douban_url = models.URLField(
        verbose_name="豆瓣url", null=True, blank=True, db_comment='豆瓣url')

    def __str__(self):
        return self.name or "暂无书名"

    class Meta:
        db_table = "dedao_book"
        verbose_name = "图书"
        verbose_name_plural = "01.图书"
        db_table_comment = '图书表'


class BookChatpter(BaseModel):
    # 单选：章节类型
    CHAPTER_TYPE_CHOICES = [
        ('C', '章'), ('E', '回'), ('V', '卷'), ('S',
                                             '节'), ('P', '部分'), ('U', '单元'), ('L', '课')
    ]

    book_id = models.CharField(
        max_length=5, verbose_name="图书ID", null=True, blank=True, db_comment='图书ID')
    chapter_index = models.IntegerField(
        verbose_name="章节索引", null=True, blank=True, db_comment='章节索引')
    chapter_type = models.CharField(
        max_length=1, verbose_name="章节类型", null=True, blank=True, db_comment='章节类型', choices=CHAPTER_TYPE_CHOICES)

    chater_title = models.CharField(
        max_length=100, verbose_name="章节标题", null=True, blank=True, db_comment='章节标题')
    chapter_topic = models.CharField(
        max_length=100, verbose_name="章节主题", null=True, blank=True, db_comment='章节主题')
    key_points = models.TextField(
        verbose_name="章节重点", null=True, blank=True, db_comment='章节重点')
    sort_order = models.IntegerField(
        verbose_name="排序索引",
        default=0,
        db_index=True, null=True, blank=True,
        db_comment="权重*1000 + chapter_index，用于统一排序"
    )

    def __str__(self):
        if self.chater_title and self.chapter_index:
            return "第{}章 {}".format(self.chapter_index, self.chater_title)
        return "暂无章节"

    def save(self, *args, **kwargs):
        # 定义各类章节的优先级（数字越小，越靠前）
        TYPE_WEIGHT = {
            'V': 1,  # 卷
            'C': 2,  # 章
            'E': 2,  # 回（与章同级）
            'P': 3,  # 部分
            'U': 4,  # 单元
            'L': 5,  # 课
            'S': 6,  # 节
            'A': 7,  # 条
            'G': 8,  # 段
        }
        weight = TYPE_WEIGHT.get(self.chapter_type, 9)  # 默认最低优先级
        index = self.chapter_index or 0  # 若无索引，默认为0
        self.sort_order = weight * 1000 + index
        super().save(*args, **kwargs)

    class Meta:
        db_table = "dedao_book_chapter"
        # verbose_name = "图书章节"
        verbose_name_plural = "02.图书章节(AI版)"
        db_table_comment = '图书章节表'


class ListenBookAuthor(BaseModel):
    name = models.CharField(
        verbose_name="解读作者", null=True, blank=True, db_comment='解读作者', max_length=100)
    introduction = models.TextField(
        verbose_name="解读人简介", null=True, blank=True, db_comment='解读人简介')
    write_book_ids = models.CharField(
        verbose_name="撰写书籍ID", null=True, blank=True, db_comment='撰写书籍ID', max_length=100)

    def __str__(self):
        return self.name or "未命名解读作者"

    class Meta:
        db_table = "dedao_listen_book_author"
        verbose_name = "听书作者"
        verbose_name_plural = "07.听书作者"
        db_table_comment = '听书作者表'


class ListenBook(BaseModel):
    book_id = models.CharField(
        verbose_name="图书ID", null=True, blank=True, db_comment='图书ID', max_length=5)
    listener_id = models.CharField(
        verbose_name="解读人ID", null=True, blank=True, db_comment='解读人ID', max_length=5)
    title = models.CharField(
        verbose_name="听书标题", null=True, blank=True, db_comment='听书标题', max_length=100)
    introduction = models.CharField(
        verbose_name="简介", null=True, blank=True, db_comment='简介', max_length=100)
    gain = models.TextField(
        verbose_name="收获", null=True, blank=True, db_comment='收获')
    listen_count = models.IntegerField(
        verbose_name="收听次数", null=True, blank=True, db_comment='收听次数', default=0)
    listen_time = models.DateField(
        verbose_name="收听时间", null=True, blank=True, db_comment='收听时间')
    publish_date = models.DateField(
        verbose_name="出版日期", null=True, blank=True, db_comment='出版日期')
    dedao_url = models.URLField(
        verbose_name="得到url", null=True, blank=True, db_comment='得到url')
    fanshu_url = models.URLField(
        verbose_name="帆书url", null=True, blank=True, db_comment='帆书url')
    center_point = models.TextField(
        verbose_name="中心重点", null=True, blank=True, db_comment='中心重点')

    def __str__(self):
        return self.title or "未命名听书"

    class Meta:
        db_table = "dedao_listen_book"
        verbose_name = "听书"
        verbose_name_plural = "04.听书"
        db_table_comment = '听书表'


class BookNote(BaseModel):
    # 单选：章节类型
    CHAPTER_TYPE_CHOICES = [
        ('C', '章'), ('E', '回'), ('V', '卷'), ('S',
                                             '节'), ('P', '部分'), ('U', '单元'), ('L', '课')
    ]

    book_id = models.CharField(
        verbose_name="图书ID", max_length=50, db_index=True, db_comment='图书ID', null=True, blank=True
    )
    chapter_index = models.IntegerField(
        verbose_name="章节索引", null=True, blank=True, db_index=True, db_comment='用于排序的章节编号'
    )
    chapter_type = models.CharField(
        max_length=1,
        choices=CHAPTER_TYPE_CHOICES,
        default='C',
        verbose_name="章节类型",
        db_comment="章节单位：如 章、回、节、卷等"
    )
    chapter_title = models.CharField(
        verbose_name="章节标题", max_length=200, null=True, blank=True, db_comment='原始章节标题'
    )
    note = models.TextField(
        verbose_name="笔记", null=True, blank=True, db_comment='用户笔记内容'
    )
    like_count = models.PositiveIntegerField(
        verbose_name="点赞数", default=0, db_comment='点赞数'
    )
    comment_count = models.PositiveIntegerField(
        verbose_name="评论数", default=0, db_comment='评论数'
    )
    collect_count = models.PositiveIntegerField(
        verbose_name="收藏数", default=0, db_comment='收藏数'
    )
    share_count = models.PositiveIntegerField(
        verbose_name="分享数", default=0, db_comment='分享数'
    )
    read_count = models.PositiveIntegerField(
        verbose_name="阅读数", default=0, db_comment='阅读数'
    )
    comments = models.TextField(
        verbose_name="评论内容", null=True, blank=True, db_comment='评论原始内容（建议拆表）'
    )
    sort_order = models.IntegerField(
        verbose_name="排序索引",
        default=0,
        db_index=True,
        db_comment="权重*1000 + chapter_index，用于统一排序"
    )

    def __str__(self):
        # 使用 get_chapter_type_display() 获取中文标签
        type_display = self.get_chapter_type_display()
        index_str = f"第{self.chapter_index}{'回' if self.chapter_type == 'E' else type_display}" if self.chapter_index else ""
        title = self.chapter_title or index_str or "未命名笔记"
        return f"{title}: {self.note[:30] if self.note else '无内容'}"

    def save(self, *args, **kwargs):
        # 定义各类章节的优先级（数字越小，越靠前）
        TYPE_WEIGHT = {
            'V': 1,  # 卷
            'C': 2,  # 章
            'E': 2,  # 回（与章同级）
            'P': 3,  # 部分
            'U': 4,  # 单元
            'L': 5,  # 课
            'S': 6,  # 节
            'A': 7,  # 条
            'G': 8,  # 段
        }
        weight = TYPE_WEIGHT.get(self.chapter_type, 9)  # 默认最低优先级
        index = self.chapter_index or 0  # 若无索引，默认为0
        self.sort_order = weight * 1000 + index
        super().save(*args, **kwargs)

    class Meta:
        db_table = "dedao_book_note"
        verbose_name = "图书笔记"
        verbose_name_plural = "05.读书笔记"
        db_table_comment = '读书笔记表'
        indexes = [
            models.Index(fields=['book_id', 'chapter_index']),
            models.Index(fields=['chapter_type']),
        ]


class ListBookNote(BaseModel):
    book_id = models.CharField(
        verbose_name="图书ID", null=True, blank=True, db_comment='图书ID', max_length=5)
    listen_book_id = models.CharField(
        verbose_name="听书ID", null=True, blank=True, db_comment='听书ID', max_length=5)
    note = models.TextField(
        verbose_name="笔记", null=True, blank=True, db_comment='笔记')
    like_count = models.IntegerField(
        verbose_name="点赞数", null=True, blank=True, db_comment='点赞数')
    comment_count = models.IntegerField(
        verbose_name="评论数", null=True, blank=True, db_comment='评论数')
    collect_count = models.IntegerField(
        verbose_name="收藏数", null=True, blank=True, db_comment='收藏数')
    share_count = models.IntegerField(
        verbose_name="分享数", null=True, blank=True, db_comment='分享数')
    read_count = models.IntegerField(
        verbose_name="阅读数", null=True, blank=True, db_comment='阅读数')
    comments = models.TextField(
        verbose_name="评论内容", null=True, blank=True, db_comment='评论内容')

    def __str__(self):
        return self.note or "未命名听书笔记"

    class Meta:
        db_table = "dedao_list_book_note"
        verbose_name = "听书笔记"
        verbose_name_plural = "06.听书笔记"
        db_table_comment = '听书笔记表'
